#include "mainapp.h"
#include <QDir>
#include <QMessageBox>
#include <QTranslator>
#include <QTextStream>
#include <QFile>

//

MainApp *MainApp::app = NULL;

MainApp::MainApp ( int & argc, char ** argv  )
		: QApplication ( argc, argv ),
		m_opt() {}
//

void MainApp::Init() {
	m_opt.Default();
	m_opt.Load();

	m_win = new MainWindowImpl();

	QVariant state = m_opt.options()->value ( "winstate" );
	QVariant geometry = m_opt.options()->value ( "wingeometry" );
	if ( !state.isNull() ) m_win->restoreState ( state.toByteArray() );
	if ( !geometry.isNull() ) m_win->restoreGeometry ( geometry.toByteArray() );

	m_win->show();
	connect ( this, SIGNAL ( lastWindowClosed() ), this, SLOT ( queryQuit() ) );
}


void MainApp::queryQuit() {
	m_opt.options()->insert ( "winstate", m_win->saveState() );
	m_opt.options()->insert ( "wingeometry", m_win->saveGeometry() );
	m_opt.Save();
	delete m_win;
	quit();
}

QString MainApp::getAppDir ( void ) {
	static const QString opt_dir ( ".portage-manager" );
	static QString path;
	if ( !path.isEmpty() ) return path;

	path = QDir::homePath() + "/";
	QDir dir ( path );
	dir.mkdir ( opt_dir );
	path += opt_dir + "/";
	return path;
}

QStringList MainApp::supportedLanguages() {
	QStringList list;
	QDir lang_dir ( ":/tr/tr/" );
	list << "English";
	foreach ( QString lang_file, lang_dir.entryList() )
	list << lang_file.left ( lang_file.length() - 3 );
	return list;
}


void MainApp::setTranslation ( QString lang ) {
	static QTranslator translator;
	app->removeTranslator ( &translator );
	if ( lang != "English" ) {
		if ( translator.load ( ":/tr/tr/" + lang + ".qm" ) )
			app->installTranslator ( &translator );
		else QMessageBox::warning ( NULL, tr ( "Change language" ), tr ( "Cannot set language to " ) + lang );
	}
}


QStringList MainApp::getCategories ( bool rebuild ) {
	static QStringList lst;
	if ( rebuild )
		lst.clear();
	if ( lst.count() == 0 ) {
		QFile file ( "/usr/portage/profiles/categories" );
		if ( file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) {
			QTextStream in ( &file );
			while ( !in.atEnd() )
				lst << in.readLine();
		}
	}
	return lst;
}
